package com.conversationboard.logger;

import java.io.PrintStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;

import com.conversationboard.config.Configuration;
import com.conversationboard.config.ConnectionStrategy;
import com.conversationboard.database.Database;
import com.conversationboard.database.Queries;
import com.conversationboard.model.User;

public class Logger {

	private static PrintStream output = new ConversationBoardPrintStream(System.out);


	public static PrintStream getOutput() {
		return output;
	}


	public static void log(Date date, String message, User user, LogMessageType type) {

		Connection connection = null;

		if (user == null) {
			user = User.getAnonymousUser();
		}

		try {

			if (user.hasIpAddress()) {
				message = message + "     [IP address: " + user.getIpAddress() + "]";
			}

			Timestamp timestamp = new Timestamp(date.getTime());

			connection = Database.getConnection();
			
			PreparedStatement statement = connection.prepareStatement(Queries.WRITE_TO_ERROR_LOG);
			statement.setTimestamp(1, timestamp);
			statement.setString(2, message);
			statement.setString(3, user.getLoginId());
			statement.setString(4, type.toString());

			statement.executeUpdate();

			statement.close();

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (connection != null && !(Configuration.getInstance().getConnectionStrategy() == ConnectionStrategy.StaticConnection)) {
				try {
					connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}

	}


	public static void log(Date date, String message, User user) {
		log(date, message, user, LogMessageType.USER);
	}

}
